<template>
  <div class="swiper-container" ref="swiperContainer">
    <div class="swiper-wrapper">
      <div v-for="(img, idx) in imgurl" :key="idx" class="swiper-slide">
        <img :src="img" alt="">
      </div>
    </div>
    <div class="swiper-pagination"></div>
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
  </div>
</template>

<script>
// 使用原生 Swiper 替代 vue-awesome-swiper
import Swiper from 'swiper';
import 'swiper/css/swiper.css';

export default {
  props: {
    imgurl: {
      type: Array,
      required: true,
      default: () => []
    }
  },
  data() {
    return {
      swiper: null
    }
  },
  watch: {
    imgurl: {
      immediate: true,
      handler(newVal, oldVal) {
        // 只有数据变化时才重新初始化
        if (newVal !== oldVal) {
          this.$nextTick(this.initSwiper);
        }
      }
    }
  },
  methods: {
    initSwiper() {
      // 确保容器存在且数据已准备
      if (!this.$refs.swiperContainer) return;
      
      // 清理旧实例
      if (this.swiper) {
        this.swiper.destroy();
        this.swiper = null;
      }
      
      // 数据为空时不初始化
      if (!this.imgurl.length) return;
      
      // 使用 setTimeout 确保 DOM 完全渲染
      setTimeout(() => {
        try {
          this.swiper = new Swiper(this.$refs.swiperContainer, {
            loop: true,
            autoplay: {
              delay: 3000,
              disableOnInteraction: false
            },
            pagination: {
              el: '.swiper-pagination',
              clickable: true
            },
            navigation: {
              nextEl: '.swiper-button-next',
              prevEl: '.swiper-button-prev'
            },
            observer: true,
            observeParents: true,
            on: {
              init: () => {
                // 确保 Swiper 正确初始化
                setTimeout(() => {
                  this.swiper.update();
                }, 100);
              }
            }
          });
        } catch (e) {
          console.error('Swiper初始化失败:', e);
        }
      }, 100);
    }
  },
  mounted() {
    this.initSwiper();
  },
  beforeDestroy() {
    if (this.swiper) {
      this.swiper.destroy();
    }
  }
}
</script>

<style scoped>
.swiper-container {
  width: 100%;
  height: 300px; /* 必须设置明确高度 */
  position: relative;
}

.swiper-wrapper {
  width: 100%;
  height: 100%;
}

.swiper-slide {
  width: 100%;
  height: 100%;
}

.swiper-slide img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.swiper-pagination {
  position: absolute;
  bottom: 10px;
  left: 0;
  right: 0;
  text-align: center;
}

.swiper-button-prev,
.swiper-button-next {
  position: absolute;
  top: 50%;
  width: 30px;
  height: 30px;
  margin-top: -15px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
  color: white;
  z-index: 10;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.swiper-button-prev {
  left: 10px;
}

.swiper-button-next {
  right: 10px;
}
</style>